$(document).ready(function() {

	// Navigation menu

	$('ul#navigation').superfish({ 
		delay:       1000,
		animation:   {opacity:'show',height:'show'},
		speed:       'fast',
		autoArrows:  true,
		dropShadows: false
	});

	$('ul#navigation li').hover(function(){
		$(this).addClass('sfHover2');
	},
	function(){
		$(this).removeClass('sfHover2');
	});
	
	// Live Search
	
	//jQuery('#search-bar input[name="q"]').liveSearch({url: 'live_search.php?q='});
	
	//Hover states on the static widgets

	$('.ui-state-default').hover(
		function() { $(this).addClass('ui-state-hover'); }, 
		function() { $(this).removeClass('ui-state-hover'); }
	);

	//Sortable portlets

	$('.sortable .column').sortable({
		cursor: "move",
		connectWith: '.sortable .column',
		dropOnEmpty: false
	});

	$(".column").disableSelection();

	//Sidebar only sortable boxes
	$(".side_sort").sortable({
		axis: 'y',
		cursor: "move",
		connectWith: '.side_sort'
	});

	
	//Close/Open portlets
	$(".portlet-header").hover(function() {
		$(this).addClass("ui-portlet-hover");
	},
	function(){
		$(this).removeClass("ui-portlet-hover");
	});

	$(".portlet-header .ui-icon").click(function() {
		$(this).toggleClass("ui-icon-circle-arrow-n");
		$(this).parents(".portlet:first").find(".portlet-content").toggle();
	});


	// Sidebar close/open (with cookies)

	function close_sidebar() {
		
		$("#sidebar").addClass('closed-sidebar');
		$("#page_wrapper #page-content #page-content-wrapper").addClass("no-bg-image wrapper-full");
		$("#open_sidebar").show();
		$("#close_sidebar, .hide_sidebar").hide();
	}

	function open_sidebar() {
		$("#sidebar").removeClass('closed-sidebar');
		$("#page_wrapper #page-content #page-content-wrapper").removeClass("no-bg-image wrapper-full");
		$("#open_sidebar").hide();
		$("#close_sidebar, .hide_sidebar").show();
	}

	$('#close_sidebar').click(function(){
		close_sidebar();
		if($.browser.safari) {
		    location.reload();
		}
		$.cookie('sidebar', 'closed' );
			$(this).addClass("active");
	});
	
	$('#open_sidebar').click(function(){
		open_sidebar();
		if($.browser.safari) {
		    location.reload();
		}
		$.cookie('sidebar', 'open' );
	});
	
//	var sidebar = $.cookie('sidebar');

	//	if (sidebar == 'closed') {
		//	close_sidebar();
	 //   };

		//if (sidebar == 'open') {
		//	open_sidebar();
	 //  };

	/* Tooltip */

	// $(function() {
		// $('.tooltip').tooltip({
			// track: true,
			// delay: 0,
			// showURL: false,
			// showBody: " - ",
			// fade: 250
			// });
		// });
		
	/* Theme changer - set cookie */

    // $(function() {

        // $('a.set_theme').click(function() {
           	// var theme_name = $(this).attr("id");
			// $('body').append('<div id="theme_switcher" />');
			// $('#theme_switcher').fadeIn('fast');

			// setTimeout(function () { 
				// $('#theme_switcher').fadeOut('fast');
			// }, 2000);

			// setTimeout(function () { 
			// $("link[title='style']").attr("href","css/themes/" + theme_name + "/ui.css");
			// }, 500);

			// $.cookie('theme', theme_name );

			// $('a.set_theme').removeClass("active");
			// $(this).addClass("active");
			
        // });
		
	//	var theme = $.cookie('theme');

	//	$("a.set_theme[id="+ theme +"]").addClass("active");
	    
		// if (theme == 'black_rose') {
	        // $("link[title='style']").attr("href","css/themes/black_rose/ui.css");
	        
	    // };

		// if (theme == 'gray_standard') {
	        // $("link[title='style']").attr("href","css/themes/gray_standard/ui.css");
	    // };

		// if (theme == 'gray_lightness') {
	        // $("link[title='style']").attr("href","css/themes/gray_lightness/ui.css");
	    // };
	    
		// if (theme == 'blueberry') {
	        // $("link[title='style']").attr("href","css/themes/blueberry/ui.css");
	    // };
	    
		// if (theme == 'apple_pie') {
	        // $("link[title='style']").attr("href","css/themes/apple_pie/ui.css");
	    // };

//    });
    
	/* Layout option - Change layout from fluid to fixed with set cookie */

    // $(function() {

		// $('.layout-options a').click(function(){
			// var lay_id = $(this).attr("id");
			// $('body').attr("class",lay_id);
			// $("#page-layout, #page-header-wrapper, #sub-nav").addClass("fixed");
			// $.cookie('layout', lay_id );
			// $('.layout-options a').removeClass("active");
			// $(this).addClass("active");
		// })
			
	    // var lay_cookie = $.cookie('layout');

		// $(".layout-options a[id="+ lay_cookie +"]").addClass("active");

		// if (lay_cookie == 'layout100') {
			// $('body').attr("class","");
			// $("#page-layout, #page-header-wrapper, #sub-nav").removeClass("fixed");
	    // };

		// if (lay_cookie == 'layout90') {
			// $('body').attr("class","layout90");
			// $("#page-layout, #page-header-wrapper, #sub-nav").addClass("fixed");
	    // };
	    
		// if (lay_cookie == 'layout75') {
			// $('body').attr("class","layout75");
			// $("#page-layout, #page-header-wrapper, #sub-nav").addClass("fixed");
	    // };
	    
		// if (lay_cookie == 'layout980') {
			// $('body').attr("class","layout980");
			// $("#page-layout, #page-header-wrapper, #sub-nav").addClass("fixed");
	    // };
	    
		// if (lay_cookie == 'layout1280') {
			// $('body').attr("class","layout1280");
			// $("#page-layout, #page-header-wrapper, #sub-nav").addClass("fixed");
	    // };
	    
		// if (lay_cookie == 'layout1400') {
			// $('body').attr("class","layout1400");
			// $("#page-layout, #page-header-wrapper, #sub-nav").addClass("fixed");
	    // };
	    
		// if (lay_cookie == 'layout1600') {
			// $('body').attr("class","layout1600");
			// $("#page-layout, #page-header-wrapper, #sub-nav").addClass("fixed");
	    // };

    // });

	// Dialog			
	
/*
	// Modal Confirmation		

		$("#modal_confirmation").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			width:500,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				'Delete all items in recycle bin': function() {
					$(this).dialog('close');
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			}
		});
	
	// Dialog Link

	$('#dialog_link').click(function(){
		$('#dialog').dialog('open');
		return false;
	});
	
	// Modal Confirmation Link

	$('#modal_confirmation_link').click(function(){
		$('#modal_confirmation').dialog('open');
		return false;
	});
	*/
	// Same height

	//var sidebarHeight = $("#sidebar").height();
	//$("#page-content-wrapper").css({"minHeight" : sidebarHeight });

	// Simple drop down menu

	var myIndex, myMenu, position, space=20;
	
	$("div.sub").each(function(){
		$(this).css('left', $(this).parent().offset().left);
		$(this).slideUp('fast');
	});
	
	$(".drop-down li").hover(function(){
		$("ul",this).slideDown('fast');
		
		//get the index, set the selector, add class
		myIndex = $(".main1").index(this);
		myMenu = $(".drop-down a.btn:eq("+myIndex+")");
	}, function(){
		$("ul",this).slideUp('fast');
	});
 
	function checkInputFileAcc( o, n, min ) {
		if (o.val().length < min ) {
			o.addClass( "ui-state-error" );
			updateTipsAcc( "Please input " + n + "." );
			return false;
		} else {
			return true;
		}
	}
	
	function checkLengthAcc( o, n, min, max ) {
		if ( o.val().length > max || o.val().length < min ) {
			o.addClass( "ui-state-error" );
			updateTipsAcc( "Length of " + n + " must be between " +
				min + " and " + max + "." );
			return false;
		} else {
			return true;
		}
	}
	
	function checkLengthAcc( o, n, min, max ) {
		if ( o.val().length > max || o.val().length < min ) {
			o.addClass( "ui-state-error" );
			updateTipsAcc( "Length of " + n + " must be between " +
				min + " and " + max + "." );
			return false;
		} else {
			return true;
		}
	}

	function checkRegexpAcc( o, regexp, n ) {
		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass( "ui-state-error" );
			updateTipsAcc( n );
			return false;
		} else {
			return true;
		}
	}
	function updateTipsAcc( t ) {
		tips
			.text( t )
			.addClass( "ui-state-highlight" );
		setTimeout(function() {
			tips.removeClass( "ui-state-highlight", 1500 );
		}, 500 );

	}			
	var tips = $( ".validateTips" );
		
	$( "#dialog-Account" ).dialog({
		autoOpen: false,
		resizable:false,
		height: 500,
		width: 450,
		zIndex:9999,
		modal: true,
		open: function() { 
			tips.text( "* fields are required." );
		},
		close: function() {
			$("#Sex_1").attr('checked','checked');

		}
	});
	$( "#dialog:ui-dialog" ).dialog( "destroy" );
	function AssignValue(){
			var o = {};
			//get name and value control 
			alert($("#AccPassword").val());
			o["IsActived"] = $("#AccIsActived").attr('checked')==true?1:0 || '';
			o["SMS"] = $("#AccSMS").attr('checked')==true?'1':'0'||'0';
			o['UserName']=$("#AccUserName").val();
			o['Password']=$("#AccPassword").val();
			o['FirstName']=$("#AccFirstName").val();
			o['LastName']=$("#AccLastName").val();
			o['Email']=$("#AccEmail").val();
			o['Telephone']=$("#AccTelephone").val();
			o['PositionID']=$("#AccPositionID").val();
			o['GroupID']=$("#AccGroupID").val();
			o['BranchID']=$("#AccBranchID").val();
			return o;
		}	 
	$("#btnAccount").live('click',function(){
		var aId= $("#m_userId").val();
		//alert(aId);
		getDataAcc(  aId )
		$("#dialog-Account").dialog({'title':'My Account'});
		$("#dialog-Account").dialog("open");
		$("#dialog-Account").dialog( "option","buttons",{
			"Update":function(){
				 
				if ( checkRequireControlAcc() ) {
					SaveAccount(AssignValue(),aId); 
					$( this ).dialog( "close" );
				}
				
			}
			,"Cancel":function(){
				$( this ).dialog( "close" );
			}
		}
		);
	});
	function SaveAccount(obj,id){
			 
			$.ajax({
				type: 'POST',
				cache: false,
				url: 'a_user.php',
				data: {"m":"edit","var":obj,"id":id,"rows":0},
				success: function(data){
					//alert(data);
					alert('Update completed');
				}
			});
	}	
	function getDataAcc(id){
	 
		var dataSet={'id':id,'m':'detail'};  
		 $.ajax({
			type: 'POST',
			cache: false,
			url: 'a_user.php',
			data: dataSet,
			success: function(data){
			 
				var obj=eval('('+data+')');
				//check branch
				checkBranch_Is_HOAcc(obj['BranchID']);
				var bval = $("#m_isHo").val()==1?false:true;
				$("#AccUserName").val(obj['UserName']).attr('disabled',bval);
				$("#AccPassword").val(obj['Password']);
				$("#AccFirstName").val(obj['FirstName']);
				$("#AccLastName").val(obj['LastName']);
				$("#AccEmail").val(obj['Email']);
				$("#AccTelephone").val(obj['Telephone']);
				$("#AccPositionID").val(obj['PositionID']).attr('disabled',bval);
				$("#AccGroupID").val(obj['GroupID']).attr('disabled',bval);
				$("#AccBranchID").val(obj['BranchID']).attr('disabled',bval);
				$("#AccIsActived").attr('checked',obj['Status']=='Actived'? true:false).attr('disabled',bval);
				$("#AccSMS").attr('checked',obj['SMS']=='1'? true:false).attr('disabled',bval);
			 

			}
		});
	}
	function checkRequireControlAcc(){
			var bValid=true;
			bValid = bValid && checkInputFileAcc( $("#AccUserName"), "Username",1);
			bValid = bValid && checkInputFileAcc( $("#AccPassword"), "Password",1);
			bValid = bValid && checkInputFileAcc( $("#AccFirstName"), "First Name",1);
			bValid = bValid && checkInputFileAcc( $("#AccEmail"), "Email",1);
			bValid = bValid && checkRegexpAcc( $("#AccEmail"), /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. admin@oriental.com" );					
			bValid = bValid && checkInputFileAcc( $("#AccTelephone"), "Telephone",1);
			return bValid;
		}
		//get json group
		$.get('a_user.php',{"c":"b"},function(data){
			var obj=eval('('+data+')');	
			if (obj != null){
				 $.each(obj, function(index, text) {
					$("#AccBranchID").append(
							$('<option></option>').val(text).html(index)
						 );
				});
			}
		});
	
 		$.get('a_user.php',{"c":"g"},function(data){
			var obj=eval('('+data+')');	
			if (obj != null){
				$.each(obj, function(index, text) {
				$("#AccGroupID").append(
						$('<option></option>').val(index).html(text)
					 );
				});
			}
		});
		
 		$.get('a_user.php',{"c":"p"},function(data){
			var obj=eval('('+data+')');	
			if (obj != null){
				$.each(obj, function(index, text) {
				$("#AccPositionID").append(
						$('<option></option>').val(index).html(text)
					 );
				});
			}
		});
		
	$("#AccTelephone").keypress(function(e){
			//alert(e);
			if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
				return false;
			}
		});	
	$("#AccBranchID").live('change',function(){
			var bid= $("#AccBranchID option:selected").val();
		
			checkBranch_Is_HOAcc(bid);
	});		
	function checkBranch_Is_HOAcc(bid){
		$.ajax({
			type: 'POST',
			cache: false,
			url: 'a_user.php',
			data: {'m':'check_ho','bid':bid},
			success: function(data){
				//alert(data);
				var obj=eval('('+data+')');
				if (obj['Type']=="1"){
					$(".tr_ac_sms").show();
				}else{
					$(".tr_ac_sms").hide();
				}
			}
		});
	}
});
